﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace Cookie.Controllers
{
    public class AuthController : Controller
    {
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login() 
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(string userName,string password)
        {
            // 验证用户名和密码逻辑
            if (userName == "admin" && password == "password")
            {
                var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                //Claim中角色认证为Admin
                new Claim(ClaimTypes.Role,"Admin")


                //Claim中携带Admin
                //new Claim(ClaimTypes.Role,"Admin")
            };

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = true
                };

                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

                return RedirectToAction("Get", "WeatherForecast");
            }

            return View();
        }

        /// <summary>
        /// 注销
        /// </summary>
        public IActionResult Logout() 
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Auth");
        }

        [Authorize(Policy ="Admin")]
        public IActionResult Admin()
        {
            return View();
        }

        [AllowAnonymous]
        public IActionResult AccessDenied()
        {
            return View();
        }
    }
}
